<script setup>
import {ref} from "vue";
import axios from "axios";
import { defineEmits } from 'vue';

const emit = defineEmits(['login-event']);

function loginEvent(res) {
  if (res.status === 200 && res.data !== null && res.data !== ''){
    localStorage.setItem('user_token',res.data.user_token)
    console.log("login")
    emit('login-event');
  }else {
    alert('账号或密码错误')
  }

}
const title = ref(["登录", "注册"])
const registerOrLogin = ref(["注册账号", "返回登录"]);
const loginForm = ref({
  username: "",
  password: "",
});
const loginType = ref(0);
function registerEvent(res){
  if(res.status === 200 && res.data !== null && res.data !== ''){
    loginForm.value.username = "";
    loginForm.value.password = "";
    loginType.value = 0;
    alert('注册成功');
  }else {
    alert('存在相同用户名，注册失败');
  }
}
const register = () => {
  const url = loginType.value === 0 ? '/api/user/login' : '/api/user/register';
  axios({
    method: 'get',
    url: url,
    params: {
      username: loginForm.value.username,
      password: loginForm.value.password
    }
  }).then(res => {
    if (loginType.value === 0) {
      loginEvent(res);
    } else {
      registerEvent(res);
    }
  }).catch(err => {console.log(err);});
};
</script>

<template>
  <div class="lg-out-div">
    <p class="lg-title">{{ title[loginType] }}</p>
    <div class="lg-form">
      <p class="lg-p">用户名</p>
      <input type="text" v-model="loginForm.username"/>
      <p class="lg-p">密码</p>
      <input type="password" v-model="loginForm.password"/>
    </div>
    <div class="lg-button" @click="register()">
      <p>{{ title[loginType] }}</p>
    </div>
    <p class="lg-or" @click="loginType = loginType === 0 ? 1 : 0">{{ registerOrLogin[loginType] }}</p>
  </div>
</template>

<style scoped>
input {
  width: 300px;
  height: 30px;
  border: 0;
  border-bottom: 1px solid #aaaaaa;
  padding: 0 5px;
}

input:focus {
  outline: none;
}

.lg-p {
  color: black;
  font-size: 20px;
}

.lg-title {
  color: black;
  font-size: 30px;
  font-weight: bold;
}

.lg-or {
  color: #777777;
  cursor: pointer;
}

.lg-out-div {
  border-radius: 10px;
  border-color: #e6e6e6;
  background: white;
  width: 480px;
  height: 480px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}

.lg-form {
  width: 300px;
  height: 160px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: flex-start;
}

.lg-button {
  background: #189dc6;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10px;
  width: 200px;
  height: 50px;
  cursor: pointer;
}

.lg-button:hover {
  background: #41bedd;
}

.lg-button p {
  color: white;
  font-weight: bold;
  cursor: pointer;
  font-size: 20px;
}
</style>